package HTTPSendIntegrator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.StringTokenizer;

import javax.activation.MimetypesFileTypeMap;

public class RetrieveConf extends HTTPMmsMessage {
	public String retriveConfMessage;
	public String filePath;
	public File files[];
	
	public RetrieveConf(String filePath){
		retriveConfMessage = "";
		this.mmsMessageType =  MMS_MESSAGE_TYPE_RETRIEVE_CONF;
		this.filePath = filePath;
		files = new File("./"+filePath).listFiles();
	}
	
	public boolean isExistFile()
	{
		if(files != null)	
			return true;
		else	
			return false;
	}
	
	public String toString(){
		
		if(!isMessageTypeSet()) return "MessageType not defined";
		if(!this.isMessageDateSet()) return "MessageDate not defined";
		if(!this.isMessageIDSet()) return "MessageID not defined";
		
		retriveConfMessage += MMS_MESSAGE_TYPE + this.getMessageType() + NL;
		
		if(isTransactionIDSet())
			retriveConfMessage += MMS_TRANSACTION_ID  + this.getTransactionID() + NL;
		
		//MMBOX/MID10293123/
		
		retriveConfMessage += MMS_DATE  + this.getMessageDate() + NL;
		retriveConfMessage += MMS_MESSAGE_ID  + this.getMessageID() + NL;
		retriveConfMessage += MMS_RETRIEVE_STATUS  + this.getRetrieveStatus() + NL;
		
		int numOfBytes = 0;
		for(int i=0; i<files.length; i++)
		{
				String mimeType = new MimetypesFileTypeMap().getContentType(files[i]);
				numOfBytes+=(int) files[i].length() + mimeType.getBytes().length;
		}
		
		Random random = new Random();
		long Randomboundary = random.nextLong();
		if(Randomboundary<0) Randomboundary*=-1;
		
		retriveConfMessage+= "type=" + new MimetypesFileTypeMap().getContentType(files[0]) + NL;
		retriveConfMessage+= "start=" + files[0].getName()  + NL;
		retriveConfMessage+= "boundary=" + Randomboundary + NL;
		
		for(int i=0; i<files.length; i++)
		{
			try {

					retriveConfMessage+= NL + "--" + Randomboundary + NL;
					retriveConfMessage+= "Content-ID: " +"<" + filePath + "_" + i +">" + NL;
					retriveConfMessage+= "Content-Type: " + new MimetypesFileTypeMap().getContentType(files[i]) + NL;
					retriveConfMessage+= "Content-Location: " + files[i].getName() + NL + NL;
					numOfBytes =(int) files[i].length();
					byte[] fileInBytes = new byte[numOfBytes];
					FileInputStream inFile;
					inFile = new FileInputStream(files[i]);
					inFile.read(fileInBytes);
					String fileContent = new String(fileInBytes);
					retriveConfMessage += fileContent + NL;
					
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return retriveConfMessage;
	}
}